package com.shimao.celnet.payment.controller.api;

import com.shimao.celnet.payment.model.PPayCUPUser;
import com.shimao.celnet.payment.model.PPayCust;
import com.shimao.celnet.payment.model.request.CallIn_outCUPApplicationReqIn;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.PPayCupUserService;
import com.shimao.celnet.payment.service.PPayCustService;
import com.shimao.celnet.payment.service.impl.apiservice.CallOut_TLPublicService;
import com.shimao.celnet.payment.util.FinalUtil;
import io.swagger.annotations.Api;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;

/**
 * 银联解绑银行卡接口
 * 外部系统 → 支付系统，数据：解绑银行卡数据
 * Created by galen on 2018/11/21.
 */
@RestController
@RequestMapping(value = "/payment")
@Api("接口：pay-208(银联)-外部解绑银行卡<OutUnbindBankCardReqIn> 外部系统 → 支付系统，数据：解绑银行卡数据")
public class CallIn_OutUnbindBankCardReqInController {

    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private PPayCustService pPayCustService;

    @Autowired
    private CallOut_TLPublicService callOut_tlPublicService;

    @Autowired
    private PPayCupUserService pPayCupUserService;

    @RequestMapping(value = "/unbindBankCardReq", method = RequestMethod.POST)
    public String UnbindBankCardReq(@RequestBody @Valid CallIn_outCUPApplicationReqIn requestJson, BindingResult result){
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        logger.info("pay-208-外部银联绑卡签约确认<OutUnbindBankCardReqIn>请求JSON:" + requestJson.toString());
        //通过valid验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                logger.debug("缺少必要参数：" + error.getDefaultMessage());
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson.toString();
            }
        }
        //根据用户号和协议编码获取注册信息
        PPayCUPUser payCUPUser = pPayCupUserService.findCUPUserByMeruseridAndAgreeid(requestJson.getMeruserid(),requestJson.getAgreeid());
        if(payCUPUser == null){
            retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS, "meruserid/agreeid");
            return retJson.toString();
        }
        //根据注册信息的商户id获取商户信息
        PPayCust payCust = getTLMessage(payCUPUser.getPayCustid(), FinalUtil.CUP_PAY_TYPE);
        try {
            logger.info("==================请求通联解绑开始=====================");
            //请求通联callout
            logger.info("========绑卡用户号："+payCUPUser.getPayMeruserid() +"=========商户号："+payCust.getCustId());
            Map<String, String> map = callOut_tlPublicService.unbind(payCUPUser.getPayAgreeid(),payCust);
            logger.info("========通联响应参数："+map.toString());
            if ("FAIL".equals(map.get(FinalUtil.RETCDE))){
                retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, "FAIL");
            }else {
                payCUPUser.setPayUnbundlingstatus(FinalUtil.BANKCARD_UNBOUND_STATUS);  //解绑成功
                pPayCupUserService.update(payCUPUser);
            }
        }catch (Exception e){
            logger.debug("通联异常参数：" + e.getMessage());
            retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, e.getMessage());
        }finally {

            return retJson.toString();
        }
    }
    /**
     * 根据小区sfid查询通联账户信息
     *
     * @param estateGuid
     * @return
     */
    public PPayCust getTLMessage(String estateGuid, String payType) {
        return pPayCustService.getBySfGuid1(estateGuid, payType);
    }
}
